<script setup>
  import zhCn from 'element-plus/dist/locale/zh-cn.mjs';
  import { ElMessageBox, ElNotification } from "element-plus";;
  import { useRouter, useRoute, onBeforeRouteUpdate, onBeforeRouteLeave } from 'vue-router'
  import { onMounted, reactive, ref, provide, inject, computed } from 'vue';
  // import { useCounterStore } from "@/stores/counter.js";
  import { eventBus } from '@/function/bus/index.js';
  import { uuid, getRecorderAryByDeep, getRegionByCode } from '@/function/lib/index.js';

  defineOptions({name: ''});
  const props = defineProps({});
  const emits = defineEmits(['on-ok']);
  // const { regionMap } = useCounterStore();

  const router = useRouter();
  const route = useRoute();
  const areaData = ref([]); // 地区data，侧边栏数据
  const routerName = ref(route.name); // 地图模式，echarts，TXMap，tianDiTuMap
  provide('routerName', routerName);
  const loading = ref(true);
  const defaultCode = ref('100000'); // 默认显示区域code
  const mapParams = reactive({
    codeRouteArr: [defaultCode.value],
    areaCode: defaultCode.value,
    provinceCode: '',
    cityCode: '',
    countyCode: '',
    streetCode: '',
  });
  provide('mapParams', mapParams);
  // 是否显示返回按钮
  const isShowBack = computed(() => {
    return mapParams.areaCode !== '100000';
  })
  // 当前code地区数据是否包含子区域
  const isIncludeSub = computed(() => {
    // 特殊地区，暂无geoJson数据
    const specialRegion = ['710000'];
    return !mapParams.areaCode || (getRegionByCode(mapParams.areaCode, 'children').length !== 0 && specialRegion.indexOf(mapParams.areaCode) === -1);
  })
  provide('isIncludeSub', isIncludeSub);
  // 侧边栏默认展开的节点
  const defaultExpandedKeys = computed(() => {
    return mapParams.codeRouteArr.map(item => String(item))
  })
  // 事件总线绑定事件，地图地图区域变化
  eventBus.on('areaChange', (params = {}) => {
    params.code = String(params.data.code)
    params.codePath = getRecorderAryByDeep({
      targetData: areaData.value,
      targetValue: String(params.data.code),
      label: {valueKey: 'code', childKey: 'children', resultKey: 'code'}
    }).join('-');
    aeraTrigger(params);
  })
  // 初始化为全国地图
  const loadMap = async () => {
    loading.value = true;
    try {
      const mapData = await import(/* @vite-ignore */ `../../assets/json/China_Province_mapping.json`)
      areaData.value = mapData.default;
      mapParams.codeRouteArr = [defaultCode.value];
      mapParams.areaCode = defaultCode.value;
      mapParams.provinceCode = '';
      mapParams.cityCode = '';
      mapParams.countyCode = '';
      mapParams.streetCode = '';
      const paramsCode = mapParams.areaCode + (isIncludeSub.value ? '_full' : '');
      mapParams.geoJSON = await fetch(`https://geo.datav.aliyun.com/areas_v3/bound/${paramsCode}.json`).then(res => res.json()).then(data => {
        return data;
      })
    } catch (error) {
      console.error(error);
    }
    loading.value = false;
  }
  // 菜单栏区域触发联动
  const aeraTrigger = async (item) => {
    loading.value = true;
    const codeList = item.codePath.split('-');
    mapParams.codeRouteArr = codeList;
    mapParams.areaCode = item.code;
    mapParams.provinceCode = codeList[0] || '';
    mapParams.cityCode = codeList[1] || '';
    mapParams.countyCode = codeList[2] || '';
    mapParams.streetCode = codeList[3] || '';
    if(isIncludeSub.value) {
      // _full：是否包含子区域
      mapParams.geoJSON = await fetch(`https://geo.datav.aliyun.com/areas_v3/bound/${mapParams.areaCode}_full.json`).then(res => res.json()).then(data => {
        return data;
      })
    } else {
      mapParams.geoJSON = await fetch(`https://geo.datav.aliyun.com/areas_v3/bound/${mapParams.areaCode}.json`).then(res => res.json()).then(data => {
        return data;
      })
    }
    loading.value = false;
  }
  
  const goToMap = async (name) => {
    loading.value = true;
    if(name === 'back') {
      // 当前所在区域code已回退到最顶级code，禁止返回
      if(mapParams.areaCode === '100000') {
        loading.value = false;
        ElNotification.error({
          title: '提示！',
          message: '已到达当前最大边界，无法继续查看！'
        })
        return
      }
      // 要前往的code
      let targetCode = '';
      switch (mapParams.codeRouteArr.length) {
        case 1:
          targetCode = '100000';
          mapParams.codeRouteArr = [];
          break;
        default:
          targetCode = mapParams.codeRouteArr.at(-2);
          mapParams.codeRouteArr = mapParams.codeRouteArr.splice(mapParams.codeRouteArr.length - 2, mapParams.codeRouteArr.length - 1)
          break;
      }
      let codePath = getRecorderAryByDeep({
        targetData: areaData.value,
        targetValue: String(targetCode),
        label: {valueKey: 'code', childKey: 'children', resultKey: 'code'}
      }).join('-')
      aeraTrigger({
        code: targetCode,
        codePath,
      });
    } else {
      router.push({ name: name });
    }
    loading.value = false;
  }

  onMounted(async () => {
    routerName.value = route.name;
    await loadMap();
  });

  // 导航守卫，组件被复用时触发
  onBeforeRouteUpdate(async (to, from) => {
    routerName.value = to.name;
    await loadMap();
  })

  // 子组件暴露
  defineExpose({});

</script>

<template>
  <div class="mapBox">
    <div class="left">
      <el-tree node-key="code" :data="areaData"
        :default-expanded-keys="defaultExpandedKeys"
        :props="{
          children: 'children',
          label: 'name',
        }" @node-click="aeraTrigger" />
    </div>
    <div class="right">
      <div class="top">
        <div class="top_left">
          <el-button :type="routerName === 'echarts' ? 'success' : 'primary'" @click="goToMap('echarts')">echarts</el-button>
          <el-button :type="routerName === 'TianDiTuMap' ? 'success' : 'primary'" @click="goToMap('TianDiTuMap')">天地图</el-button>
          <el-button :type="routerName === 'TXMap' ? 'success' : 'primary'" @click="goToMap('TXMap')">腾讯地图</el-button>
        </div>
        <div class="top_right">
          <el-button type="primary" v-if="isShowBack" @click="goToMap('back')">返回</el-button>
        </div>
      </div>
      <div class="bottom">
        <el-config-provider :locale="zhCn" style="height: 100%;width: 100%;">
          <div v-loading="loading" element-loading-text="努力加载中，请稍后..." id="main" style="height: 100%;width: 100%;">
            <RouterView></RouterView>
          </div>
        </el-config-provider>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.mapBox {
  height: 100vh;
  width: 100vw;
  overflow-y: auto;
  display: flex;
  background: #fff;
  .left {
    height: 100%;
    flex-basis: 200px;
    flex-shrink: 0;
    padding: 10px 20px 10px 0;
    overflow-y: auto;
  }
  .right {
    flex: 1;
    position: relative;
    .top {
      width: 100%;
      position: absolute;
      z-index: 999;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .top_left {}
      .top_right {}
    }
    .bottom {
      height: 100%;
      width: 100%;
    }
  }
}
</style>
